package com.fastfood.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.fastfood.model.dto.Role;

public class RoleDAO {

	public boolean addRole(Connection conn, Role role) {
		String query = "insert into roles (name) values (?)";
		boolean result = false;
		try {
			PreparedStatement preparedStatement = conn.prepareStatement(query);
			preparedStatement.setString(1, role.getName());
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public boolean deleteRole(Connection conn, Role role) {
		String query = "delete from roles where id = ?";
		boolean result = false;
		try {
			PreparedStatement preparedStatement = conn.prepareStatement(query);
			preparedStatement.setInt(1, role.getId());
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public boolean updateRole(Connection conn, Role role) {
		String query = "update roles set name = ? where id = ?";
		boolean result = false;
		try {
			PreparedStatement preparedStatement = conn.prepareStatement(query);
			preparedStatement.setString(1, role.getName());
			preparedStatement.setInt(3, role.getId());
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public Role getRoleById(Connection conn, int id) {
		Role role = null;
		try {
			ResultSet result = conn.createStatement().executeQuery("select * from roles where id = " + id);
			if (result.next()) {
				role = new Role();
				role.setId(result.getInt("id"));
				role.setName(result.getString("name"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return role;
	}
	
	public List<Role> getAllRoles(Connection conn) {
		List<Role> roles = null;
		try {
			ResultSet result = conn.createStatement().executeQuery("select * from roles");
			roles = new ArrayList<Role>();
			while (result.next()) {
				Role temp = new Role();
				temp.setId(result.getInt("id"));
				temp.setName(result.getString("name"));
				
				roles.add(temp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return roles;
	}
}
